<template>
  <div >
    <basic-layout title="签订个人授权委托书" backBtnType="arrow" :showAddBtn="false" class="wrapBox">
      <div class="body_box_main" style="background: white">
        <div class="body_box" style="background: white">
          <van-row class="listCon">
            <van-pull-refresh class="vanScroller" v-model="refreshing" @refresh="onRefresh">
              <van-list class="vanList" v-model="loading" :finished="finished">
                <div class="mainStyle" style="margin-top: 10px;font-size: 16px">
                  <div>
                    <div v-if="employee">
                      委托人姓名: <b>{{ employee.name }}</b>
                    </div>
                    <div v-if="employee">
                      委托人身份证号: <b>{{ employee.sfzh }}</b>
                    </div>
                    <div>
                      受托人单位: <b>国网武汉公司员工健康服务中心</b>
                    </div>
                    <br>
                    <div>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      基于以下共识，兹授权受托人在以下范围内附条件依法合规收集、存储、使用本人体检报告：
                    </div>
                    <div>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      1.受托人对本人体检报告及电子健康档案严格履行保密责任，切实防范健康信息泄露风险。
                    </div>
                    <div>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      2.坚持建档与服务相结合，电子健康档案仅用于职业病防治等用途；依个人授权用于开展健康监测、健康评估、健康分析等增值服务。
                    </div>
                    <div>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      3.基于健康监测、健康评估、健康分析等增值服务需要以评估病情、分级诊疗、急慢分治为前提，避免资源挤兑的工作原则，在申请上述增值服务时授权单位健康管理人员及医疗专家查阅医疗电子档案，单位健康管理人员及医疗专家对本人体检报告严格履行保密责。
                    </div>
                    <div>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      4.体检机构依此授权委托书向受托人提供、移交本人全部体检资料。
                    </div>
                    <br>
                    <div>
                      本授权书于签字之日生效。
                    </div>
                    <div>
                      特此授权。
                    </div>

                  </div>

                  <div>
                    <van-form ref="formData" class="vanForm">

                      <van-field clickable
                                 required
                                 readonly
                                 name="picker"
                                 :value="formData.startDate"
                                 label="授权开始时间"/>

                      <van-field clickable
                                 required
                                 name="picker"
                                 :value="formData.endDate"
                                 label="授权结束时间"
                                 @click="showEndDate = true"/>

                      <van-field name="签字" label="签字"  required >
                        <template #input>
                          <div>
                            <van-button
                              type="primary"
                              size="small"
                              @click="showSignature=true">点击签字</van-button>

                            <img v-if="signatureImage" :src="signatureImage"  style="border:1px solid #000;margin-top: 5px;width: 100%">
                          </div>
                        </template>
                      </van-field>

                    </van-form>

                    <van-button class="defaultBtn" size="large" color="#4eb3e9" @click="onSubmit">提交</van-button>

                  </div>
                </div>
              </van-list>
            </van-pull-refresh>
          </van-row>


        </div>

      </div>

    </basic-layout>

    <!--      请选择预约时间-->
    <van-calendar :min-date="minDate" :max-date="maxDate" :allow-same-day="true" :show-confirm="false"
                  v-model="showEndDate" @confirm="selectData" />

    <!--      签字-->
    <van-popup v-model="showSignature">
      <div>
        <canvas v-show="!signatureImage" ref="canvas" :width="canvasWidth" :height="canvasHeight" @touchstart="startDrawing"
                @touchmove="draw" @touchend="stopDrawing" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"
                @mouseout="stopDrawing"></canvas>
        <img v-show="signatureImage" :src="signatureImage" alt="签名">
        <div style="display: flex;">
          <van-button size="large" @click="clearCanvas">清空</van-button>
          <van-button size="large" color="#4eb3e9" @click="saveSignature">保存签名</van-button>
        </div>
      </div>
    </van-popup>

    <full-loading v-if="loading"></full-loading>
  </div>
</template>
<script>
import { ImagePreview } from 'vant';
import { queryFileList } from "@api/common";
import {  addPower } from "@/api/realAssets/rvhealth/power";
import { getEmployeeByUserId } from "@/api/realAssets/rvhealth/baseEmployee";
import { signUpload} from "@/api/realAssets/rvhealth/common";

export default {
  name: "applyPowerAdd",
  props: {},
  components: {},
  data() {
    return {

      //加载
      refreshing: false,
      loading: false,
      finished: false,

      //员工信息
      employee: null,

      // 表单参数
      formData: {
        userId: JSON.parse(sessionStorage.getItem("userInfo")).userId,
        startDate: null,
        endDate: null,
        signCode: "", //签字图片
      },

      //预约时间展示
      minDate: new Date(),
      maxDate: new Date(new Date().getFullYear() + 100, 11, 31),
      showEndDate: false,

      //签字
      showSignature:false,
      signatureImage: null, //签字图片路径
      isDrawing: false,
      canvasWidth: 300,
      canvasHeight: 200,
      isSignatureEmpty:true

    };
  },
  created() {},
  computed: {},
  beforeMount() {
    //获得当前用户的信息
    this.getEmployee();

    //初始化时间
    this.formData.startDate = this.getStartDate();
    this.formData.endDate = this.getEndDate();
  },
  mounted() {},
  methods: {
    //获得当前用户的信息
    getEmployee(){
      this.loading = true;
      this.finished = false;
      getEmployeeByUserId({userId: JSON.parse(sessionStorage.getItem("userInfo")).userId}).then(response => {
        this.employee = response.data.data;

        if(null == response.data.data){
          this.$Notify({type: 'danger', message: '查无此人，请联系系统管理员'});
        }

        this.loading = false;
        this.finished = true;
      }).catch(() => {
        this.loading = false;
        this.finished = true;
      });
    },


    //选择预约时间
    selectData(item) {
      // console.log(item)
      // console.log(item.format("yyyy-MM-dd"))

      this.formData.endDate = item.format("yyyy-MM-dd");
      this.showEndDate = false;

    },

    //获得今日日期
    getStartDate() {
      let date = new Date(),
        year = date.getFullYear(), // 获取完整的年份(4位)
        month = date.getMonth() + 1, // 获取当前月份(0-11,0代表1月)
        strDate = date.getDate(); // 获取当前日(1-31)

      if (month < 10) month = `0${month}`; // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}`; // 如果日是个位数，在前面补0

      // 返回格式为 YYYY-mm-dd 的日期字符串
      return `${year}-${month}-${strDate}`;
    },
    //获得十年后的日期
    getEndDate() {
      let date = new Date(),
        year = date.getFullYear() + 10, // 获取完整的年份(4位)
        month = date.getMonth() + 1, // 获取当前月份(0-11,0代表1月)
        strDate = date.getDate(); // 获取当前日(1-31)

      if (month < 10) month = `0${month}`; // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}`; // 如果日是个位数，在前面补0

      // 返回格式为 YYYY-mm-dd 的日期字符串
      return `${year}-${month}-${strDate}`;
    },

    //刷新
    onRefresh() {
      this.refreshing = false;
      //查询表格数据
      this.getEmployee();
    },

    // 提交
    onSubmit() {
      //图片数据校验
      if (this.formData.startDate == null) {
        this.$Notify({type: 'warning', message: "请授权开始时间"});
        return;
      }
      if (this.formData.endDate == null) {
        this.$Notify({type: 'warning', message: "请授权结束时间"});
        return;
      }

      //签字
      if (this.formData.signCode === "") {
        this.$Notify({type: 'warning', message: "请签字！"});
        return;
      }

      //加载
      this.loading = true;
      //新增房屋申请审批:首租
      addPower(this.formData).then(response => {
        this.$Notify({type: 'success', message: '签订成功！'});
        //返回上一页
        this.$router.go(-1);
        //加载
        this.loading = false;
      });
    },

    //签字-清空
    clearCanvas() {
      this.signatureImage = null;
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);
      this.isSignatureEmpty = true;
    },
    //签字-开始画画
    startDrawing(event) {
      this.isDrawing = true;
      this.draw(event);
    },
    //签字-正在画画
    draw(event) {
      if (!this.isDrawing) return;
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');
      context.lineWidth = 2;
      context.lineCap = 'round';
      context.strokeStyle = '#000';
      const rect = canvas.getBoundingClientRect();
      const x = event.touches[0].clientX - rect.left;
      const y = event.touches[0].clientY - rect.top;
      context.lineTo(x, y);
      context.stroke();
      context.beginPath();
      context.moveTo(x, y);
      this.isSignatureEmpty = false;
    },
    //签字-停止画画
    stopDrawing() {
      this.isDrawing = false;
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');
      context.beginPath();
    },
    //签字-保存
    saveSignature() {
      if (this.isSignatureEmpty) {
        this.$Notify({type: 'warning', message: "请签名后保存"});
        return;
      }
      const canvas = this.$refs.canvas;
      const dataURL = canvas.toDataURL();
      this.signatureImage = dataURL;
      this.$emit('signature', dataURL);

      //关闭画布
      this.showSignature = false;

      //上传图片并回显
      let formData=new FormData();
      formData.append('file',this.base64ImgtoFile(dataURL));

      //请求接口 -- 签名上传
      signUpload(formData).then(result=>{
        //这里进行获取到result之后的操作
        //console.log( result );

        this.formData.signCode = result.data.fileCode;
      });
    },
    // 附：base64转化成图片
    base64ImgtoFile(dataurl, fileName='file') {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1]);
      let n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${fileName}.${suffix}`, { type: mime });
    },


    calcMargin(index) {
      if (index == 0) {
        return '10px 0px';
      } else {
        return '0px 0px 10px 0px';
      }
    },


  },
};
</script>
<style lang="less" scoped>
.update-box {
  width: 270px;
}
.sign-box {
  padding: 10px;
  box-sizing: border-box;
}
.showUpdateWin-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;

  .btn {
    margin: 0 5px;
  }
}

.finish-btn {
  position: absolute;
  right: 0;
  bottom: -8px;

  :last-child {
    color: #fff !important;
  }

  .btn {
    margin: 0 5px;
  }
}
.body_box_main {
  background-color: #f9f9f9;
  height: 100%;


  .body_box {
    background-color: #f9f9f9;
    height: 100%;

    .listCon {
      height: 100%;

      .vanScroller {
        height: 100%;
        overflow-y: auto;

        &::-webkit-scrollbar {
          width: 0px !important;
          height: 0px !important;
        }

        .vanList {

          .mainStyle {
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: space-between;
            background: rgb(255, 255, 255);
            color: rgb(51, 51, 51);
            border: 1px solid rgb(220, 223, 230);
            border-radius: 6px;
            //max-height: 300px;
            padding: 5px 10px 0px 10px;

            .main_01 {
              flex-direction: column;
              justify-content: space-around;
              width: 100%;

              .main_01_top {
                height: 40px;
                width: 100%;
                font-size: 16px;
                font-weight: 600;
                display: flex;
                justify-content: space-between;
                align-items: center;
                position: relative;
                border-bottom: 1px solid #eee;

                .title {
                  display: flex;

                  .vanTagStyle {

                    .title_span {
                      color: #f69b52;
                      font-weight: 600;
                    }
                  }
                }

                .yystatusStyle {
                  color: #3CB371;
                  font-size: 13px;
                }

                .noyystatusStyle {
                  color: #808080;
                  font-size: 13px;
                }

              }

              .midStyle {
                max-height: 200px;
                width: 100%;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                position: relative;
                margin-bottom: 10px;

                .van-ellipsis {
                  color: #9e9e9f;
                  margin-top: 5px;
                  height: 24px;
                  line-height: 24px;

                  span:first-child {
                    font-size: 14px;
                  }

                  span:last-child {
                    font-size: 14px;
                    color: #504f4f;
                  }

                }
              }
            }
          }

        }
      }
    }
  }
}

/deep/ .van-tabs {
  height: 100%;
}

/deep/ .van-tabs__content {
  height: calc(100% - 44px);
}

/deep/ .van-tab__pane {
  height: 100%;
}


.midMain {
  //max-height: 120px;
  max-height: 120px;
  //min-height: 80px;
  //height: 100px;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  position: relative;
  border-bottom: 1px solid #eee;

  .topContent {
    color: #9e9e9f;
    margin-top: 5px;
    height: 24px;
    line-height: 24px;

    span:first-child {
      font-size: 14px;
    }

    span:last-child {
      font-size: 14px;
      color: #504f4f;
    }
  }

  .buttonContent {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 5px;

    .left {
      width: 80%;

      .f {
        color: #9e9e9f;
        margin-top: 5px;
        //height: 24px;
        //line-height: 24px;

        span:first-child {
          font-size: 14px;
        }

        span:last-child {
          font-size: 14px;
          color: #504f4f;
        }
      }


      .s {
        color: #9e9e9f;
        margin-top: 5px;
        margin-bottom: 5px;
        height: 24px;
        line-height: 24px;

        span:first-child {
          font-size: 14px;
        }

        span:last-child {
          font-size: 14px;
          color: #504f4f;
        }
      }

    }

    .left_02 {
      width: 100%;

      .f {
        color: #9e9e9f;
        margin-top: 5px;
        //height: 24px;
        //line-height: 24px;

        span:first-child {
          font-size: 14px;
        }

        span:last-child {
          font-size: 14px;
          color: #504f4f;
        }
      }


      .s {
        color: #9e9e9f;
        margin-top: 5px;
        margin-bottom: 5px;
        height: 24px;
        line-height: 24px;

        span:first-child {
          font-size: 14px;
        }

        span:last-child {
          font-size: 14px;
          color: #504f4f;
        }
      }

    }


    .btn {
      width: 20%;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .van-button {
        padding: 0 10px;
        height: 30px;
        line-height: 30px;
        border-radius: 17px;
        font-size: 13px;
      }
    }
  }

  //&:before {
  //  content: '';
  //  position: absolute;
  //  margin-top: 100px;
  //  width: 100%;
  //  height: 1px;
  //  background: #8080804a;
  //}

}

.flexBtn {
  display: flex;
  justify-content: space-between;

  div {
    flex: 1;
    text-align: center;
    height: 40px;
    line-height: 40px;
    color: #1e93ff;
    font-size: 15px;
  }

  p {
    flex: 1;
    text-align: center;
    height: 40px;
    line-height: 40px;
    color: #1e93ff;
    font-size: 15px;
  }

  div:nth-of-type(1) {
    box-sizing: border-box;
    border-right: 1px solid #eee;
    color: #f25454;
  }
}
</style>
